<?php
/**
 * Created by PhpStorm.
 * User: mr_lee
 * Date: 2017/10/16
 * Time: 下午2:07
 */

namespace app\leadertest\controller;


use app\common\controller\ActionLogs;
use app\common\model\CardStore;
use app\common\controller\AdminBase;
use app\common\model\ActionLog;
use app\common\model\DeviceMicro;
use app\common\model\DevicePrint;

use app\common\model\Huifu;
use app\common\model\HuifuLog;
use app\common\model\Merchant;
use app\common\model\Momerchant;
use app\common\model\MerchantCashier;
use app\common\model\MerchantCate;
use app\common\model\MerchantContent;
use app\common\model\Prints;
use app\common\model\WxOpen;
use Bank\HuifuServer;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;

class Momach extends AdminBase
{

    //商户列表
    public function momachlist()
    {
        //搜索条件
        $request = request();
        $p_data = $request->get();
        unset($p_data['page']);
        $map = [];
        if ($p_data) {
            $map['merchant_name'] = array('like', '%' . trim($p_data['merchant_name']) . '%');
        } else {
            $p_data['merchant_name'] = '';
        }
        $Momerchant = new Momerchant();
        $map['agent'] = array('in', $this->getagentlist());

        $momach = $Momerchant->where($map)->paginate(10, false, ['query' => request()->param()]);

        $Mercate = new MerchantCate();
        $momachlist = $Momerchant->where($map)->select();
        $map_cate['parent_id'] = 0;
        $map_cate['status'] = 0;
        $level = $Mercate->where($map_cate)->select();
        $this->assign('momachlist', $momachlist);
        $this->assign('momach', $momach);
        $this->assign('p_data', $p_data);
        $this->assign('level', $level);
        return $this->fetch();
    }

    public function machtobanklist(Request $request)
    {

        if ($request->isAjax()) {
            $param = $request->post();
            $Huifu = new Huifu();
            $map['agentid'] = ['in', $this->getagentlist()];
            $list = $Huifu->where($map)->limit(($param['pageNumber'] - 1) * $param['pageSize'], $param['pageSize'])->order('id desc')->select();
            foreach ($list as $k => $v) {
                $list[$k]['status'] = getm2bstatu($v['status']);
            }
            $re_param["total"] = $Huifu->count();
            //获取的记录
            $re_param["rows"] = collection($list)->toArray();;
            return json($re_param);
        } else {
            return $this->fetch('machtobanklist');
        }

    }

    public function machtobankquery(Request $request)
    {
        if ($request->isAjax()) {

            $param = $request->post();
            $map['id'] = $param['id'];
            $Huifu = new Huifu();
            $info = $Huifu->where($map)->find();
            if ($param['method'] == "query") {
                switch ($info['status']) {
                    case 1:
                        $re_param = $this->huifu_join_mach($info);

                        break;
                    case 4:
                        $data['status'] = 94;
                        $re_param = $this->huifu_modify_mach($info);
                        break;
                    case 5:
                        $data['status'] = 95;
                        $re_param = $this->huifu_modify_jiesuan($info);
                        break;
                }

            } elseif ($param['method'] == "cancel") {
                $data['remark'] = $param['remark'];
                switch ($info['status']) {
                    case 1:
                        $data['status'] = 99;

                        break;
                    case 4:
                        $data['status'] = 94;
                        break;
                    case 5:
                        $data['status'] = 95;
                        break;
                }
                $up = $Huifu->save($data, $map);
                if ($up) {
                    $re_param['result_code'] = "SUCCESS";
                    $re_param['result_msg'] = "操作成功";
                } else {
                    $re_param['result_code'] = "FAIL";
                    $re_param['result_msg'] = "操作失败";
                }

            }

            return json($re_param);


        } else {
            $Huifu = new Huifu();
            $info = $Huifu->where('id', $request->param('id'))->find();
            $this->assign('info', $info);
            return $this->fetch();
        }
    }

    //修改商户结算信息
    private function huifu_modify_jiesuan($param)
    {
//        $JsonData['memberId'] = $param['merchid'];
//        $JsonData['agentId'] = $param['memberId'];
//        $JsonData['newBankActId'] = $param['bankActId'];
//        $JsonData['newBankActName'] = $param['bankActName'];
//        $JsonData['newBankCityId'] = "130400";
//        $JsonData['newBankId'] = "01030000";
//        $JsonData['newBankProvId'] = "130000";
//        $JsonData['newIsPrivate'] = $param['isPrivate'];
////        $JsonData['pictureIds']['archFlph01'] = $this->huifu_upload($param, $param['archFlph01'], "01", $type = 1);//营业执照
////        $JsonData['pictureIds']['archFlph04'] = $this->huifu_upload($param, $param['archFlph01'], "04", $type = 1);;//开户许可证
////        $JsonData['pictureIds']['archFlph05'] = $this->huifu_upload($param, $param['archFlph01'], "05", $type = 1);;//法人身份证
////        $JsonData['pictureIds']['archFlph06'] = $this->huifu_upload($param, $param['archFlph01'], "06", $type = 1);;//法人身份证
//        $JsonData3 = json_encode($JsonData, JSON_UNESCAPED_UNICODE);
//        $HuifuServer = new HuifuServer();
//        $salt = "chinapnr";
//        $ss2 = hash("sha256", $JsonData3 . $salt);
//        $data['checkValue'] = $ss2;
//        $data['jsonData'] = $JsonData3;
//        $res = $HuifuServer->change_act($data);
//        return $res;
//
//        if ($res['respCode'] == "0001") {
//            $re_param['result_code'] = "SUCCESS";
//            $re_param['result_msg'] = $res['respMsg'];
//            $re_param['info'] = $res['jsonData'];
//            $sdata['status'] = 7;
//            $Huifu = new Huifu();
//            $Huifu->save($sdata, ['id', $param['id']]);
//        } else {
//            $re_param['result_code'] = "FAIL";
//            $re_param['result_msg'] = $res['respMsg'];
//        }
//        return $re_param;
    }

    //修改商户信息提交
    private function huifu_modify_mach($param)
    {
        $JsonData['merchName'] = $param['merchName'];//商户名称
        $JsonData['merchShortName'] = $param['merchShortName'];//商户简称
        $JsonData['userDefinedName'] = $param['userDefinedName'];
        $JsonData['regProvId'] = $param['regProvId'];
        $JsonData['regCityId'] = $param['regCityId'];
        $JsonData['regAreaId'] = $param['regAreaId'];
        $JsonData['regAddr'] = $param['regAddr'];
        $JsonData['provId'] = $param['regProvId'];
        $JsonData['cityId'] = $param['regCityId'];
        $JsonData['areaId'] = $param['regAreaId'];
        $JsonData['merchAddr'] = $param['merchAddr'];
        $JsonData['legalName'] = $param['legalName'];
        $JsonData['idType'] = $param['idType'];
        $JsonData['idNo'] = $param['idNo'];
        $JsonData['idValidType'] = $param['idValidType'];
        $JsonData['idSdate'] = $param['idSdate'];
        if ($param['idValidType'] == 1) {
            $JsonData['idEdate'] = $param['idEdate'];
        }
        $JsonData['contactName'] = $param['contactName'];
        $JsonData['contactIdType'] = $param['contactIdType'];
        $JsonData['contactIdNo'] = $param['contactIdNo'];
        $JsonData['contactIdValidType'] = $param['contactIdValidType'];
        $JsonData['contactIdSdate'] = $param['contactIdSdate'];
        if ($param['contactIdValidType'] == 1) {
            $JsonData['contactIdEdate'] = $param['contactIdEdate'];
        }
        $JsonData['contactTelno'] = $param['contactTelno'];
        $JsonData['contactEmail'] = $param['contactEmail'];
        $JsonData['isCreditCode'] = $param['isCreditCode'];//是否三证合一
        if ($param['isCreditCode'] == 1) {
            $JsonData['creditCode'] = $param['creditCode'];//统一社会信用代码证编号
        } else {

            $JsonData['regCode'] = $param['regCode'];//营业执照编号
            $JsonData['orgCode'] = $param['orgCode'];//组织机构代码证编号
        }
        $JsonData['licType'] = $param['licType'];//证件有效期类型
        $JsonData['licSdate'] = $param['licSdate'];//
        if ($param['licType'] == 1) {
            $JsonData['licEdate'] = $param['licEdate'];
        }
        $JsonData['settleTerm'] = $param['settleTerm'];
        $JsonData['fee01'] = $param['fee01'];
        $JsonData['fee08'] = $param['fee08'];
        $JsonData['fee12'] = $param['fee12'];
        $JsonData['pictureIds']['archFlph01'] = $this->huifu_upload($param, $param['archFlph01'], "01", $type = 1);//营业执照
        $JsonData['pictureIds']['archFlph04'] = $this->huifu_upload($param, $param['archFlph01'], "04", $type = 1);;//开户许可证
        $JsonData['pictureIds']['archFlph05'] = $this->huifu_upload($param, $param['archFlph01'], "05", $type = 1);;//法人身份证
        $JsonData['pictureIds']['archFlph06'] = $this->huifu_upload($param, $param['archFlph01'], "06", $type = 1);;//法人身份证
        $JsonData['bgRetUrl'] = $param['bgRetUrl'];
        $JsonData3 = json_encode($JsonData, JSON_UNESCAPED_UNICODE);
        $HuifuServer = new HuifuServer();
        $salt = "chinapnr";
        $ss2 = hash("sha256", $JsonData3 . $salt);
        $data['checkValue'] = $ss2;
        $data['jsonData'] = $JsonData3;
        $res = $HuifuServer->mch_updata($data);
        if ($res['respCode'] == "0001") {
            $this->huifu_log($JsonData['reqSerialNum'], $param['id'],2);
            $re_param['result_code'] = "SUCCESS";
            $re_param['result_msg'] = $res['respMsg'];
            $re_param['info'] = $res['jsonData'];
            $sdata['status'] = 6;
            $Huifu = new Huifu();
            $Huifu->save($sdata, ['id', $param['id']]);
        } else {
            $re_param['result_code'] = "FAIL";
            $re_param['result_msg'] = $res['respMsg'];
        }
        return $re_param;

    }

    //商户信息提交
    private function huifu_join_mach($param)
    {

        $JsonData['merchClass'] = 1;//商户性质 企业 个体
        $JsonData['merchType'] = $param['merchType'];//商户类型 连锁 单店
        if ($param['merchType'] == 1) {
            $JsonData['relatedMerchName'] = $param['relatedMerchName'];//连锁商户主商户号
        }
        $JsonData['merchName'] = $param['merchName'];//商户名称
        $JsonData['merchShortName'] = $param['merchShortName'];//商户简称
        $JsonData['userDefinedName'] = $param['merchShortName'];
        $JsonData['regProvId'] = $param['regProvId'];
        $JsonData['regCityId'] = $param['regCityId'];
        $JsonData['regAreaId'] = $param['regAreaId'];
        $JsonData['regAddr'] = $param['regAddr'];
        $JsonData['provId'] = $param['provId'];
        $JsonData['cityId'] = $param['cityId'];
        $JsonData['areaId'] = $param['areaId'];
        $JsonData['merchAddr'] = $param['merchAddr'];
        $JsonData['businessShours'] = $param['businessShours'];
        $JsonData['businessEhours'] = $param['businessEhours'];
        $JsonData['isCreditCode'] = $param['isCreditCode'];//是否三证合一
        if ($param['isCreditCode'] == 1) {
            $JsonData['creditCode'] = $param['creditCode'];//统一社会信用代码证编号
        } else {
            $JsonData['regCode'] = $param['regCode'];//营业执照编号
            $JsonData['orgCode'] = $param['orgCode'];//组织机构代码证编号
        }
        $JsonData['licType'] = $param['licType'];//证件有效期类型
        $JsonData['licSdate'] = $param['licSdate'];//
        if ($param['licType'] == 1) {
            $JsonData['licEdate'] = $param['licEdate'];
        }
        $JsonData['cateType'] = $param['cateType'];//商户经营类型 1实体 2虚拟
        if ($param['merchClass'] == 1) {
            $JsonData['legalName'] = $param['legalName'];
            $JsonData['idType'] = $param['idType'];
            $JsonData['idNo'] = $param['idNo'];
            $JsonData['idValidType'] = $param['idValidType'];
            $JsonData['idSdate'] = $param['idSdate'];
            if ($param['idType'] == 1) {
                $JsonData['idEdate'] = $param['idEdate'];
            }
        }
        $JsonData['contactName'] = $param['contactName'];
        $JsonData['contactIdType'] = $param['contactIdType'];
        $JsonData['contactIdNo'] = $param['contactIdNo'];
        $JsonData['contactIdValidType'] = $param['contactIdValidType'];
        $JsonData['contactIdSdate'] = $param['contactIdSdate'];
        if ($param['contactIdValidType'] == 1) {
            $JsonData['contactIdEdate'] = $param['contactIdEdate'];
        }
        $JsonData['contactTelno'] = $param['contactTelno'];
        $JsonData['contactEmail'] = $param['contactEmail'];
        $JsonData['contractNum'] = $param['contractNum'];
        $JsonData['signName'] = $param['signName'];
        $JsonData['signDate'] = $param['signDate'];
        $JsonData['signSdate'] = $param['signSdate'];
        $JsonData['signEdate'] = $param['signEdate'];
        $JsonData['tellerId'] = $param['tellerId'];;
        $JsonData['isSendMes'] = $param['isSendMes'];;
        $JsonData['isPrivate'] = $param['isPrivate'];;
        $JsonData['bankActName'] = $param['bankActName'];;
        $JsonData['bankActId'] = $param['bankActId'];;
        $JsonData['bankProvId'] = $param['bankProvId'];;
        $JsonData['bankCityId'] = $param['bankCityId'];;
        $JsonData['bankAreaId'] = $param['bankAreaId'];;
        $JsonData['bankName'] = $param['bankName'];;
        $JsonData['settleTerm'] = $param['settleTerm'];
        $JsonData['fee01'] = $param['fee01'];
        if ($param['isPrivate'] == 1) {
            $JsonData['accountIdType'] = $param['accountIdType'];
            $JsonData['accountIdNo'] = $param['accountIdNo'];
            $JsonData['accountIdValidType'] = $param['accountIdValidType'];
            $JsonData['accountIdSdate'] = $param['accountIdSdate'];
            if ($param['accountIdValidType'] == 1) {
                $JsonData['accountIdEdate'] = $param['accountIdEdate'];

            }

        }
        $JsonData['auth23'] = 0;
        $JsonData['auth24'] = 0;
        //微信配置
        $JsonData['auth18'] = $param['auth18'];
        if($param['auth38']==1){
            $JsonData['auth38'] = $param['auth38'];
            $JsonData['fee33'] = $param['fee33'];
            $JsonData['wxAppid'] = $param['wxAppid'];
        }

        if ($param['auth18'] == 1) {
            $JsonData['wechatCateCode'] = $param['wechatCateCode'];
            $JsonData['fee08'] = $param['fee08'];
            $JsonData['isMerWechat'] = 0;
        }
        //阿里配置
        $JsonData['auth19'] = $param['auth19'];;
        if ($param['auth19'] == 1) {
            $JsonData['alipayCateCode'] = $param['alipayCateCode'];;
            $JsonData['fee12'] = $param['fee12'];
        }
        $JsonData['bgRetUrl'] = $param['bgRetUrl'];
        $JsonData['reqSerialNum'] = $param['reqSerialNum'];
        $JsonData['pnrpayMerType'] = $param['pnrpayMerType'];;
        $JsonData['picUploadWay'] = "01";;
        $JsonData['memberId'] = $param['memberId'];//代理商会员号
        $JsonData['opTellerId'] = $param['opTellerId'];//代理商编号
//        $JsonData['archFlph01'] = $this->huifu_upload($param, $param['archFlph01'], "01", $type = 0);//营业执照
//        $JsonData['archFlph04'] = $this->huifu_upload($param, $param['archFlph01'], "04", $type = 0);;//开户许可证
//        $JsonData['archFlph05'] = $this->huifu_upload($param, $param['archFlph01'], "05", $type = 0);;//法人身份证
//        $JsonData['archFlph06'] = $this->huifu_upload($param, $param['archFlph01'], "06", $type = 0);;//法人身份证
        $JsonData['reqSerialNum'] = "wn_join-" . date('YmdHis') . rand(100, 999);;
        $JsonData3 = json_encode($JsonData, JSON_UNESCAPED_UNICODE);
//        return $JsonData3;
        $HuifuServer = new HuifuServer();
        $salt = "chinapnr";
        $ss2 = hash("sha256", $JsonData3 . $salt);
        $data['checkValue'] = $ss2;
        $data['jsonData'] = $JsonData3;
//        return $data;
        $res = $HuifuServer->mch_join($data); 
        $this->huifu_log($JsonData['reqSerialNum'], $param['id'],'add');
        if ($res['respCode'] == "0001") {
            $re_param['result_code'] = "SUCCESS";
            $re_param['result_msg'] = $res['respMsg'];
            $re_param['info'] = $res;
            $sdata['status'] = 2;
            $Huifu = new Huifu();
            $Huifu->save($sdata, ['id'=>$param['id']]);

        } else {
            $re_param['result_code'] = "FAIL";
            $re_param['result_msg'] = $res['respMsg'];
        }
        return $re_param;
    }

    private function huifu_log($reqSerialNum, $hid,$type)
    {
        $data['reqSerialNum'] = $reqSerialNum;
        $data['hid'] = $hid;
        $data['status'] = 1;
        $data['type'] = $type;
        $HuifuLog = new HuifuLog();
        $HuifuLog->save($data);

    }

    //汇付天下上传图片
    public function huifu_upload($param, $url, $photoType, $type = 0)
    {
        //      01:营业执照图片
//02:税务登记证
//03:组织机构代码证
//04:开户许可证
//05:法人身份证正面
//06:法人身份证反面
//07:结算人身份证正面
//08:结算人身份证反面
//09:商务协议
//10:公司照片一
//11:公司照片二
//12:公司照片三
//13:联系人身份证正面
//14:联系人身份证反面
        $HuifuServer = new HuifuServer();
        $img = $HuifuServer->download_image($url, $fileName = '01', "down");
        $data['picture'] = "@" . $img['saveDir'] . "/" . $img['fileName'];

        $JsonData['agentId'] = $param['memberId'];
        if ($type == 1) {
            $JsonData['memberId'] = $param['merchid'];
        }
        $JsonData['photoType'] = $photoType;
//        $JsonData['reqSerialNum'] = "test";
        $salt = "chinapnr";
        $ss2 = hash("sha256", json_encode($JsonData, JSON_UNESCAPED_UNICODE) . $salt);
        $data['checkValue'] = $ss2;
        $data['jsonData'] = json_encode($JsonData, JSON_UNESCAPED_UNICODE);
        $res = $HuifuServer->upload_img($data);
        if ($res['respCode'] == "0000") {
//            $re_param['result_code'] = "SUCCESS";
//            $re_param['result_msg'] = $res['respDesc'];
//            $re_param['info'] = $res['jsonData'];
            $infos = json_decode($res['jsonData'], true);
            $re_param = $infos['pictureID'];
        } else {
            $re_param = "";
//            $re_param['result_msg'] = $res['respDesc'];
        }
        return $re_param;


    }

    //门店列表
    public function machlist()
    {
        //搜索条件
        $request = request();
        $p_data = $request->get();
        $top_mid = $request->param('top_mid');
        unset($p_data['page']);
        $map = [];
        if ($p_data) {
            $map['merchant'] = array('like', '%' . trim($p_data['merchant']) . '%');
        } else {
            $p_data['merchant'] = '';
        }
        $Merchant = new Merchant();
        $map['top_mid'] = $top_mid;
        $map['agent'] = array('in', $this->getagentlist());
        $mach = $Merchant->where($map)->paginate(10, false, ['query' => request()->get()]);
        $Mercate = new MerchantCate();
        $map_cate['parent_id'] = 0;
        $map_cate['status'] = 0;
        $level = $Mercate->where($map_cate)->select();
        $mab['top_mid'] = $top_mid;
        $mab['agent'] = array('in', $this->getagentlist());
        $machlist = $Merchant->where($mab)->select();
        $this->assign('machlist', $machlist);
        $this->assign('p_data', $p_data);
        $this->assign('level', $level);
        $this->assign('mach', $mach);
        return $this->fetch();

    }

    //商户详情
    public function momachinfo()
    {
        $request = request();
        $param = $request->get();
        $id = $request->param('id');
        $map['id'] = $id;
        $Momerchant = new Momerchant();
        $map['agent'] = array('in', $this->getagentlist());
        $user = $Momerchant->where(array('id' => $param['id']))->find();
        $wxopen = WxOpen::get($user['wx_open_id']);
        $this->assign('wxopen', $wxopen);
        $MerchantCashier = new MerchantCashier();
        $cashier = $MerchantCashier->where('top_mid', $id)->select();
        $this->assign('cashier', $cashier);
        $this->assign('user', $user);
        return $this->fetch();
    }

    //门店详情
    public function machinfo()
    {
        $request = request();
        $param = $request->get();
        $id = $request->param('id');
        $map['id'] = $id;
        $Merchant = new Merchant();
        $map['agent'] = array('in', $this->getagentlist());
        $user = $Merchant->where($map)->relation('MerchantContent')->find();
        var_dump($Merchant->getLastSql());
        $wxopen = WxOpen::get($user['wx_open_id']);
        $this->assign('wxopen', $wxopen);
        $MerchantCashier = new MerchantCashier();
        $mac['mid'] = $user['id'];
        $cashier = $MerchantCashier->where($mac)->select();
        $this->assign('cashier', $cashier);
        $this->assign('user', $user);
        return $this->fetch();
    }

    /*
     * 获取二维码
     *
     */
    public function getqrcode()
    {
        $arr = request()->param();
//        file_put_contents('/data2/html/payos/test.txt', 'admin_getqrcode-1' . json_encode($arr), FILE_APPEND);
        $jg = action('Qrcodes/qrcode', array(request()->param('mid'), "https://" . $_SERVER['HTTP_HOST'] . "/index.php?s=/Index/pay/id/" . request()->param('mid') . ".html"));
//        file_put_contents('/data2/html/payos/test.txt', 'admin_getqrcode-2' . json_encode($jg), FILE_APPEND);
        $qr = $jg;
        $length = filesize($qr);
        $type = mime_content_type($qr);
        $showname = ltrim(strrchr($qr, '/'), '/');
        header("Content-Description: File Transfer");
        header('Content-type: ' . $type);
        header('Content-Length:' . $length);
        if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) { //for IE
            header('Content-Disposition: attachment; filename="' . rawurlencode($showname) . '"');
        } else {
            header('Content-Disposition: attachment; filename="' . $showname . '"');
        }
        readfile($qr);
        exit;
    }

    /*
     * 获取二维码
     */
    public function getmercode()
    {
        $arr = request()->param();
//        file_put_contents('/data2/html/payos/test.txt', 'admin_getmercode-1' . json_encode($arr), FILE_APPEND);
        $map['id'] = request()->param('mid');
        $Merchant = new Merchant();
        $merchant = $Merchant->where($map)->value('merchant');
        $jg = action('Qrcodes/mercode', array(request()->param('mid'), 48, "https://" . $_SERVER['HTTP_HOST'] . "/index.php?s=/Index/pay/id/" . request()->param('mid') . ".html", $merchant));
//        file_put_contents('/data2/html/payos/test.txt', 'admin_getmercode-2' . json_encode($jg), FILE_APPEND);
        $qr = $jg;
        $length = filesize($qr);
        $type = mime_content_type($qr);
        $showname = ltrim(strrchr($qr, '/'), '/');
        header("Content-Description: File Transfer");
        header('Content-type: ' . $type);
        header('Content-Length:' . $length);
        if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) { //for IE
            header('Content-Disposition: attachment; filename="' . rawurlencode($showname) . '"');
        } else {
            header('Content-Disposition: attachment; filename="' . $showname . '"');
        }
        readfile($qr);
        exit;
    }

    /*
     * 获取二维码地址
     * */
    public function get_mer_code()
    {
        $mid = request()->param('mid');
        $url = '/qrcode/' . $mid . '.png';
        return $url;
    }

    //获取设备列表
    public function device_micro_view()
    {
        if (request()->isAjax()) {
            $map['mid'] = request()->post('mid');
            $list = DeviceMicro::where($map)->select();
            return json($list);
        }
    }

    //修改退款密码
    public function device_micro_md_pass()
    {
        if (request()->isAjax()) {
            $map['id'] = request()->post('id');
            $data['tk_pass'] = MD5(request()->post('tk_pass'));
            $DeviceMirco = new DeviceMicro();
            $sa = $DeviceMirco->save($data, $map);
            if ($sa) {
                $arr = array('code' => 0, 'message' => "退款密码修改成功");
            } else {
                $arr = array('code' => 1, 'message' => "退款密码修改失败");
            }
            return json($arr);
        }
    }

    //解绑设备
    public function device_mirco_jb()
    {
        if (request()->isAjax()) {
            $map['id'] = request()->post('id');
            $data['device_code'] = null;
            $data['status'] = 0;
            $DeviceMirco = new DeviceMicro();
            $sa = $DeviceMirco->save($data, $map);
            if ($sa) {
                $arr = array('code' => 0, 'message' => "解绑设备成功");
            } else {
                $arr = array('code' => 1, 'message' => "解绑设备失败");
            }
            return json($arr);
        }
    }

    /*
     * 添加设备
     * */
    public function add_device_micro()
    {
        if (request()->isAjax()) {
            $data['mid'] = request()->post('mid');
            $data['device_name'] = request()->post('device_name');
            $data['code'] = action('common/pub/generate_code');
            $data['is_tk'] = request()->post('is_tk');
            $data['tk_pass'] = MD5(request()->post('tk_pass'));
            $DeviceMirco = new DeviceMicro();
            $save = $DeviceMirco->save($data);
            if ($save) {
                $arr = array('code' => 0, 'message' => '添加成功');
            } else {
                $arr = array('code' => 1, 'message' => '添加失败');
            }
            return json($arr);
        }
    }

    /*
     * 删除门店
     * */
    public function delmach()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            //     return json($arr);
            if ($this->get_qx_mid($arr['id'])) {
                $map['id'] = $arr['id'];
                $Merchant = new Merchant();
                $res = $Merchant->where($map)->delete();
                if ($res) {
                    $data = [
                        'code' => '0',
                        'message' => '删除成功！'
                    ];
                } else {
                    $data = [
                        'code' => '9001',
                        'message' => '删除失败！'
                    ];
                }
            } else {
                $data = [
                    'code' => '9999',
                    'message' => '您没有权限处理该商户！'
                ];
            }
            return json($data);
        }
    }

    /*
     * 获取门店列表
     * */
    public function getmachlist()
    {
        if (Request()->isAjax()) {
            $Merchant = new Merchant();
            $map['id'] = array('in', $this->get_mer_mid());
            $list = $Merchant->where($map)->paginate('10');
            return json($list);
        }
    }

    /*
     * 获取门店列表
     * */
    public function getstorelist()
    {
        if (Request()->isAjax()) {
            $CardStore = new CardStore();
            $top_mid = Session::get('login_top_mid');
            $map['top_mid'] = array('in', $top_mid);
            $list = $CardStore->where($map)->paginate('10');
            if ($list == false) {
                $data['code'] = 9001;
                $data['list'] = 0;
            } else {
                if (empty($list)) {
                    $data['code'] = 9002;
                    $data['list'] = 0;
                } else {
                    $data['code'] = 0;
                    $data['list'] = $list;
                }
            }
            return json($data);
        }
    }

    //添加打印机
    public function addprint()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            if ($this->get_qx_mid($arr['mid'])) {
                $rules = $this->validate($arr, ['username' => 'require', 'ukey' => 'require', 'sn' => 'require']);
                if (true !== $rules) {
                    // 验证失败 输出错误信息
                    dump($rules);
                } else {
                    $sarr = Session::get('user');
                    $DevicePrint = new DevicePrint();
                    $arrs['username'] = $arr['username'];
                    $arrs['ukey'] = $arr['ukey'];
                    $arrs['sbname'] = $arr['sbname'];
                    $arrs['sn'] = $arr['sn'];
                    $arrs['mid'] = $arr['mid'];
                    $arrs['addtime'] = time();
                    $arrs['adduser'] = $sarr['nickname'];
                    $arrs['leixing'] = 'print';
                    $res = $DevicePrint->save($arrs);
                    if ($res) {
                        $data['code'] = '0';
                        $data['message'] = '添加成功！';
                    } else {
                        $data['code'] = '9001';
                        $data['message'] = '添加失败！';
                    }
                }
            } else {
                $data['code'] = '9999';
                $data['message'] = '您没有权限处理该商户！';
            }
            return json($data);
        }
    }

    //打印机列表
    public function listprint()
    {
        if (Request()->isAjax()) {
            $map['mid'] = request()->post('id');
            $DevicePrint = new DevicePrint();
            $printlist = $DevicePrint->where($map)->select();
            if ($printlist) {
                $this->assign('list', $printlist);
                return $this->fetch();
            }
        }
    }

    //删除打印机
    public function delprint()
    {
        if (Request()->isAjax()) {
            $id = request()->post('id');
            $map['id'] = $id;
            $DevicePrint = new DevicePrint();
            $res = $DevicePrint->where($map)->delete();
            if ($res) {
                $data['code'] = '0';
                $data['message'] = '移除成功！';
            } else {
                $data['code'] = '9001';
                $data['message'] = '移除失败！';
            }
            return json($data);
        }
    }

    /*
     * 打开授权
     * */
    public function open_auth()
    {

        $request = request();
        $System = new \app\common\model\System();
        $config = $System->where(array('id' => 1))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
        );
        $weObj = new Wxobjopen($options);
        $pre_auth_code = $weObj->get_pre_auth_code();
        if (!$request->get('auth_code')) {
            $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
            $callback = $http_type . $_SERVER['HTTP_HOST'] . url("mach/open_auth", $_GET);
            $url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=" . $config['component_appid'] . "&pre_auth_code=" . $pre_auth_code . "&redirect_uri=" . $callback;
            header("Location: $url");
            exit();
        } else {
            $appinfo = $weObj->authorization_info($request->get('auth_code'));
            $auth_appid = $appinfo['authorization_info']['authorizer_appid'];
            $auther['component_appid'] = $config['component_appid'];
            $auther['authorizer_appid'] = $auth_appid;
            $auther_info = $weObj->get_auther_info($auther);
            if ($auther_info['authorizer_info']['service_type_info']['id'] == 2 && ($auther_info['authorizer_info']['verify_type_info']['id'] == 0 || $auther_info['authorizer_info']['verify_type_info']['id'] == 3)) {
                $data['gh_nick_name'] = $auther_info['authorizer_info']['nick_name'];
                $data['service_type_info'] = $auther_info['authorizer_info']['service_type_info']['id'];
                $data['verify_type_info'] = $auther_info['authorizer_info']['verify_type_info']['id'];
                $data['gh_id'] = $auther_info['authorizer_info']['user_name'];
                $data['alias'] = $auther_info['authorizer_info']['alias'];
                $data['qrcode_url'] = $auther_info['authorizer_info']['qrcode_url'];
                $data['principal_name'] = $auther_info['authorizer_info']['principal_name'];
                $data['wx_open_info'] = json_encode($auther_info, JSON_UNESCAPED_UNICODE);
                $data['authorizer_appid'] = $auth_appid;
                $data['authorizer_refresh_token'] = $appinfo['authorization_info']['authorizer_refresh_token'];
                $data['at_access_token'] = $appinfo['authorization_info']['authorizer_access_token'];
                $data['at_addtime'] = time();
                $data['at_expires_in'] = 7000;
                $data['addtime'] = time();
                $data['zt'] = 1;
                $func_info = "";
                foreach ($appinfo['authorization_info']['func_info'] as $k => $v) {
                    $func_info .= $v['funcscope_category']['id'] . ',';
                }
                $WxOpen = new WxOpen();
                $data['func_info'] = $func_info;
                $wx_open = $WxOpen->where(array('authorizer_appid' => $appinfo['authorization_info']['authorizer_appid']))->find();
                if ($wx_open) {
                    $sj = $WxOpen->save($data, ['authorizer_appid' => $appinfo['authorization_info']['authorizer_appid']]);
                    $da2['wx_open_id'] = $wx_open['id'];
                } else {
                    $sj = $WxOpen->save($data);
                    $da2['wx_open_id'] = $WxOpen->id;
                }
                $da2['auth_type'] = 1;
                $mss['id'] = request()->param('id');
                $Merchant = new Merchant();
                $Merchant->save($da2, $mss);
                if ($sj) {
                    $this->success('授权成功', url("mach/machinfo") . "?id=" . request()->param('id'));
                } else {
                    $this->error('授权失败');
                }
            } else {
                $this->error('该公众号为订阅号或者未通过微信认证，请确认后重新授权');
            }
        }
    }
}